from rest_framework_simplejwt.serializers import TokenObtainSlidingSerializer,TokenObtainPairSerializer
from rest_framework_simplejwt.settings import api_settings
from django.contrib.auth.models import update_last_login
from rest_framework.exceptions import ValidationError
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView
from  rest_framework.pagination import PageNumberPagination
from rest_framework.views import Response
from collections import OrderedDict
from rest_framework import status

class AdminTokenObtainSlidingSerializer(TokenObtainPairSerializer):
    """管理员登录返回指定数据业务逻辑"""

    # def validate(self, attrs):
    #     data = super().validate(attrs)
    #     if self.user.is_staff==0:#判断是否是管理员用户
    #         raise ValidationError('不是管理员用户')
    #
    #     token = self.get_token(self.user)
    #
    #     data["token"] = 'Bearer '+str(token)
    #     data['username']=self.user.username
    #     data['id']=self.user.id
    #
    #     if api_settings.UPDATE_LAST_LOGIN:
    #         update_last_login(None, self.user)
    #
    #     return data

    def validate(self, attrs):
        data = super().validate(attrs)
        if self.user.is_staff==0:#判断是否是管理员用户
            raise ValidationError('不是管理员用户')

        refresh = self.get_token(self.user)
        token = self.get_token(self.user)
        data["refresh"] = str(refresh)
        data["token"] = 'Bearer '+str(refresh.access_token)
        data['username']=self.user.username
        data['id']=self.user.id


        if api_settings.UPDATE_LAST_LOGIN:
            update_last_login(None, self.user)

        return data


class AdminTokenObtainPairView(TokenObtainPairView):
    serializer_class = AdminTokenObtainSlidingSerializer



class UtilsPageNumberPagination(PageNumberPagination):
    """分页类"""
    page_size=5
    page_size_query_param  = 'pagesize'
    max_page_size = 20

    #设置分页类返回指定数据
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('lists', data),
            ('page',self.page.number),
            ('pages',self.page.paginator.num_pages),
            ('pagesize',self.page.paginator.per_page)
        ]))

def private_authorization(obj):
    """自定义权限认证"""
    if obj.request.user.is_staff != True:
        return Response({'err':'权限不足'},status=status.HTTP_200_OK)




